package com.buyuphk.buyupdeskproject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

/**
 * author: JianfeiMa
 * email: majianfei93@163.com
 * created date: 2019-11-26 09:06
 */
public class MyTimerTask extends TimerTask {
    private MySQLiteHelper mySQLiteHelper;
    private DateTimeFormatter dateTimeFormatter;

    public MyTimerTask(MySQLiteHelper mySQLiteHelper) {
        this.mySQLiteHelper = mySQLiteHelper;
        dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    }

    @Override
    public void run() {
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        int month = localDate.getMonthValue();
        int day = localDate.getDayOfMonth();
        String sYear = String.valueOf(year);
        String sMonth = String.valueOf(month);
        String sDay = String.valueOf(day);
        String sDate = sYear + "_" + sMonth + "_" + sDay;
        String willCheckFilePath = "D:\\P\\" + sDate;
        File file = new File(willCheckFilePath);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files != null) {
                List<String> url = new ArrayList<String>();
                for (int i = 0; i < files.length; i ++) {
                    File childFile = files[i];
                    System.out.println(LocalDateTime.now().format(dateTimeFormatter) + " san_parent_directory:" + childFile);
                    File[] imageFileArray = childFile.listFiles();
                    if (imageFileArray != null && imageFileArray.length > 0) {
                        for (int j = 0; j < imageFileArray.length; j ++) {
                            File imageFile = imageFileArray[j];
                            //System.out.println(LocalDateTime.now().format(dateTimeFormatter) + " scan_image_file:" + imageFile.getName());
                            boolean result = mySQLiteHelper.read(imageFile.getName());
                            if (!result) {
                                String absolutePath = imageFile.getAbsolutePath();
                                url.add(absolutePath);
                            }
                        }
                    }
                }
                if (url.size() > 0) {
                    System.out.println(LocalDateTime.now().format(dateTimeFormatter) + " have new file");
                    String[] url1 = new String[url.size()];
                    for (int i = 0; i < url.size(); i++) {
                        url1[i] = url.get(i);
                    }
                    String result = uploadFile("http://192.168.1.33:8081/sell1/restFileController/uploadFile", sDate, url1);
                    System.out.println(LocalDateTime.now().format(dateTimeFormatter) + " upload_result:" + result);
                } else {
                    System.out.println(LocalDateTime.now().format(dateTimeFormatter) + " no have new file");
                }
            }
        }
    }

    /**
     * 多文件上传的方法
     *
     * @param actionUrl：上传的路径
     * @param uploadFilePaths：需要上传的文件路径，数组
     * @return
     */
    @SuppressWarnings("finally")
    public String uploadFile(String actionUrl, String localDate, String[] uploadFilePaths) {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        DataOutputStream dataOutputStream = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        try {
            // 统一资源
            URL url = new URL(actionUrl);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;

            // 设置是否从httpUrlConnection读入，默认情况下是true;
            httpURLConnection.setDoInput(true);
            // 设置是否向httpUrlConnection输出
            httpURLConnection.setDoOutput(true);
            // Post 请求不能使用缓存
            httpURLConnection.setUseCaches(false);
            // 设定请求的方法，默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码连接参数
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置请求内容类型
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            // 设置DataOutputStream
            dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.writeBytes(twoHyphens + boundary + end);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"date\";" + end);
            dataOutputStream.writeBytes(end);
            dataOutputStream.writeBytes(localDate);
            dataOutputStream.writeBytes(end);

            for (int i = 0; i < uploadFilePaths.length; i++) {
                String uploadFile = uploadFilePaths[i];
                String[] splitResult = uploadFile.split("\\\\");
                String parentDirectory = splitResult[splitResult.length - 2];
                String filename = uploadFile.substring(uploadFile.lastIndexOf("\\") + 1);
                String relativePath = parentDirectory + File.separator + filename;
                String oneWrite = twoHyphens + boundary + end;
                dataOutputStream.writeBytes(oneWrite);
                String s = "Content-Disposition: form-data; " + "name=\"files" + "\";filename=\"" + relativePath + "\"" + end;
                dataOutputStream.writeBytes(s);
                dataOutputStream.writeBytes(end);
                FileInputStream fileInputStream = new FileInputStream(uploadFile);
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int length = -1;
                while ((length = fileInputStream.read(buffer)) != -1) {
                    dataOutputStream.write(buffer, 0, length);
                }
                dataOutputStream.writeBytes(end);
                /* close streams */
                fileInputStream.close();
            }
            String finalWrite = twoHyphens + boundary + twoHyphens + end;
            dataOutputStream.writeBytes(finalWrite);
            /* close streams */
            dataOutputStream.flush();
            System.out.println(LocalDateTime.now().format(dateTimeFormatter) + " image upload end");
            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                reader = new BufferedReader(inputStreamReader);
                tempLine = null;
                resultBuffer = new StringBuffer();
                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                    resultBuffer.append("\n");
                }
                mySQLiteHelper.create(uploadFilePaths);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dataOutputStream != null) {
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultBuffer.toString();
        }
    }
}
